﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Practice.API.Controllers
{
    /// <summary>
    /// 文件操作控制器
    /// </summary>
    [Route("file")]
    [ApiController]
    public class FileController : ControllerBase
    {

        IWebHostEnvironment _host;


       

        public FileController(IWebHostEnvironment host)
        {
            _host = host;
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Upload() //IFormFileCollection files
        {

            var files = Request.Form.Files;
            //验证参数
            if (files.Count <= 0)
            {
                return BadRequest(new { code = 601, message = "请选择文件" });
            }
            string[] exts = { ".png", ".jpg", ".jpeg", ".gif" };
            List<string> list = this.UploadFile(files,size:1);



            #region 5行上传
            ////保存路径
            //var path = "wwwroot/images/" + item.FileName;
            ////保存文件
            //using(var stream =System.IO.File.OpenWrite(path))
            //{
            //    item.CopyTo(stream);
            //}
            #endregion

            return Ok(list);
        }


        private List<string> UploadFile(IFormFileCollection files, string[]? exts = null, int size = 0)
        {
            List<string> list = new();
            //批量上传：也是一张一张保存
            foreach (var item in files)
            {
                //1、服务器路径
                var wwwroot = _host.WebRootPath;
                var date = System.DateTime.Now.ToString("yyyyMMdd");
                var path = $"{wwwroot}/{date}/";
                //判断文件夹是否存在
                if (!System.IO.Directory.Exists(path))
                {
                    //不存在则创建
                    Directory.CreateDirectory(path);
                }

                //2、文件重命名  原文件名：1.jpg  新文件名：safafasfdas-asfdasfdas-afasfd.jpg
                var extName = Path.GetExtension(item.FileName); //获取文件的扩展名
                var newFileName = Guid.NewGuid().ToString("N");
                newFileName = $"{newFileName}{extName}";

                //3、文件格式
                //string[] exts = { ".png", ".jpg", ".jpeg", ".gif" };
                if (exts != null && exts.Length > 0)
                {
                    if (!exts.ToList().Contains(extName))
                    {
                        //return BadRequest(new { code = 602, message = "文件格式不对" });
                    }
                }

                //4、文件大小 示例：不能超过1m
                // 1G = 1024M   1M = 1024Kb  1Kb = 1024b
                if (size > 0)
                {
                    var len = item.Length; //文件大小
                    if (len > size * 1024 * 1024)
                    {
                        // return BadRequest(new { code = 602, message = "超过文件最大上传限制1M" });
                    }
                }

                var filePath = Path.Combine(path, newFileName); //文件路径

                //保存文件
                using (var stream = System.IO.File.OpenWrite(filePath))
                {
                    item.CopyTo(stream);
                    list.Add($"{date}/{newFileName}");

                }
            }
            return list;
        }

        

    }
}
